package org.red5.websocket;


import org.red5.entity.Message;
import org.red5.entity.R;
import org.red5.entity.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName WebsocketAPI
 * @Description //Websocket 推送消息接口
 * @Author 武玉锋
 * @Date 2019-07-25 16:46:
 **/
@Controller
@RequestMapping("/webSocket")
public class WebsocketDemo {

    @Autowired
    private WebsocketAPI websocketAPI;
    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;

    @PostMapping("/send")
    @ResponseBody
    public R send(@RequestParam String message) {
        websocketAPI.sendAlarmMessage(0,message);
        return R.ok();
    }


    @PostMapping("/sendImm")
    @ResponseBody
    public R sendImm(@RequestParam String message) {
        List<String> keys=webAgentSessionRegistry.getAllSessionIds().entrySet()
                .stream().map(Map.Entry::getKey)
                .collect(Collectors.toList());

        websocketAPI.sendMessageImm(0,message);
        return R.ok();
    }
    @PostMapping("/sendEchartImm")
    @ResponseBody
    public R sendEchartImm(@RequestParam String message) {
        List<String> keys=webAgentSessionRegistry.getAllSessionIds().entrySet()
                .stream().map(Map.Entry::getKey)
                .collect(Collectors.toList());

        websocketAPI.sendEchartImm(0,message);
        return R.ok();
    }

    @MessageMapping("/welcome") // 浏览器发送请求通过@messageMapping 映射/welcome 这个地址。
    @SendTo("/topic/getResponse") // 服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
    public Response say(Message message) throws Exception {
        Thread.sleep(1000);
        return new Response(0,"Welcome, " + message.getName() + "!");
    }
}
